from django.core.paginator import Paginator
from django.views.generic import View

from goods.models import GoodsCategory,GoodsChannel
from goods.models import SKU
from contents.models import ContentCategory
from collections import OrderedDict

from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import SKUSerializer

# Create your views here.
class CategoryView(View):
    """
    获取首页分类数据

    GET /goods/categories/
    """
    def get(self,request):
        pass


########################################## 热销商品排行 ################################################
from rest_framework_extensions.cache.mixins import ListCacheResponseMixin
class HotSKUListView(ListCacheResponseMixin,ListAPIView):
    """
    获取热销商品
    GET /goods/categories/(?P<category_id>\d+)/hotskus/
    """
    serializer_class = SKUSerializer
    pagination_class = None
    def get_queryset(self):
        category_id = self.kwargs.get('category_id')

        return SKU.objects.filter(category_id=category_id,is_launched=True).order_by('-sales')[:3]


############################################# sku商品列表 ##############################################
class SKUListView(APIView):

    def get(self,request,category_id):

        page = request.query_params.get('page')
        page_size = request.query_params.get('page_size')
        ordering = request.query_params.get('ordering')

        sku_set = SKU.objects.filter(category_id=category_id,is_launched=True).order_by(ordering).all()
        if not sku_set:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        count = sku_set.count()    #计算sku商品总量
        Page_set = Paginator(sku_set,page_size) #获取分页集合
        cur_page_obj = Page_set.page(int(page)).object_list #获取当前页数据对象
        serializer = SKUSerializer(cur_page_obj,many=True)  #序列化器做序列化处理

        data = {
            'count':count,
            'results':serializer.data
        }
        return Response(data=data)


############################################# sku商品搜索视图 ##############################################
from drf_haystack.viewsets import HaystackViewSet
from .serializers import SKUSearchSerializer
class GoodsSearchViewSet(HaystackViewSet):

    serializer_class = SKUSearchSerializer

    index_models = [SKU]


############################################# 获取sku商品的评论信息 ##############################################
from orders.models import OrderGoods
from .serializers import SKUCommentListSerializer
class SKUCommentListView(APIView):
    def get(self,request,sku_id):
        query_set = OrderGoods.objects.filter(sku=sku_id,is_commented=True).order_by('-update_time')
        serializer = SKUCommentListSerializer(query_set,many=True)
        return Response(serializer.data)




